import React, { useState, useEffect, useCallback } from 'react';
import { Folder } from '@/utils/api';
import api from '@/utils/api';

interface FolderTreeProps {
  onFolderSelect?: (folderId: string | null) => void;
  currentFolderId?: string | null;
  userId?: string;
}

const FolderTree: React.FC<FolderTreeProps> = ({ 
  onFolderSelect, 
  currentFolderId = null,
  userId 
}) => {
  const [folders, setFolders] = useState<Folder[]>([]);
  const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
  const [contextMenu, setContextMenu] = useState<{ x: number; y: number; folder: Folder | null } | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [newFolderColor, setNewFolderColor] = useState('#3B82F6');
  const [parentFolderId, setParentFolderId] = useState<string | null>(null);

  // 加载文件夹树
  const loadFolders = useCallback(async () => {
    try {
      const response = await api.fileManager.getFolderTree(userId);
      if (response.data.success) {
        setFolders(response.data.data);
      }
    } catch (error) {
      console.error('加载文件夹树失败:', error);
    }
  }, [userId]);

  useEffect(() => {
    loadFolders();
  }, [loadFolders]);

  // 切换文件夹展开/收起
  const toggleFolder = (folderId: string) => {
    const newExpanded = new Set(expandedFolders);
    if (newExpanded.has(folderId)) {
      newExpanded.delete(folderId);
    } else {
      newExpanded.add(folderId);
    }
    setExpandedFolders(newExpanded);
  };

  // 选择文件夹
  const selectFolder = (folderId: string | null) => {
    onFolderSelect?.(folderId);
  };

  // 右键菜单
  const handleContextMenu = (e: React.MouseEvent, folder: Folder | null) => {
    e.preventDefault();
    e.stopPropagation();
    setContextMenu({ x: e.clientX, y: e.clientY, folder });
  };

  // 关闭右键菜单
  useEffect(() => {
    const handleClick = () => setContextMenu(null);
    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, []);

  // 创建文件夹
  const handleCreateFolder = async () => {
    if (!newFolderName.trim()) return;

    try {
      await api.fileManager.createFolder({
        name: newFolderName.trim(),
        parentId: parentFolderId,
        color: newFolderColor,
        userId: userId || 'anonymous',
        userName: '当前用户'
      });
      setShowCreateModal(false);
      setNewFolderName('');
      setNewFolderColor('#3B82F6');
      setParentFolderId(null);
      await loadFolders();
    } catch (error) {
      console.error('创建文件夹失败:', error);
      alert('创建文件夹失败');
    }
  };

  // 重命名文件夹
  const handleRenameFolder = async (folder: Folder) => {
    const newName = prompt('请输入新名称:', folder.name);
    if (!newName || newName === folder.name) return;

    try {
      await api.fileManager.updateFolder(folder._id, { name: newName });
      await loadFolders();
    } catch (error) {
      console.error('重命名失败:', error);
      alert('重命名失败');
    }
  };

  // 删除文件夹
  const handleDeleteFolder = async (folder: Folder) => {
    if (!confirm(`确定要删除文件夹"${folder.name}"吗？\n该操作会同时删除文件夹内的所有文件和子文件夹！`)) {
      return;
    }

    try {
      await api.fileManager.deleteFolder(folder._id, userId);
      await loadFolders();
      if (currentFolderId === folder._id) {
        selectFolder(null);
      }
    } catch (error) {
      console.error('删除文件夹失败:', error);
      alert('删除文件夹失败');
    }
  };

  // 渲染文件夹树节点
  const renderFolder = (folder: Folder, level: number = 0) => {
    const isExpanded = expandedFolders.has(folder._id);
    const isSelected = currentFolderId === folder._id;
    const hasChildren = folder.children && folder.children.length > 0;

    return (
      <div key={folder._id} style={{ paddingLeft: level * 16 + 'px' }}>
        <div
          className={`flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-100 rounded transition-colors ${
            isSelected ? 'bg-blue-50 text-blue-600' : ''
          }`}
          onClick={() => selectFolder(folder._id)}
          onContextMenu={(e) => handleContextMenu(e, folder)}
        >
          {/* 展开/收起按钮 */}
          {hasChildren ? (
            <button
              onClick={(e) => {
                e.stopPropagation();
                toggleFolder(folder._id);
              }}
              className="w-4 h-4 flex items-center justify-center text-gray-500 hover:text-gray-700"
            >
              {isExpanded ? '▼' : '▶'}
            </button>
          ) : (
            <span className="w-4"></span>
          )}

          {/* 文件夹图标 */}
          <span 
            className="text-xl" 
            style={{ color: folder.color || '#3B82F6' }}
          >
            📁
          </span>

          {/* 文件夹名称 */}
          <span className="flex-1 text-sm truncate">{folder.name}</span>

          {/* 文件数量 */}
          {folder.fileCount > 0 && (
            <span className="text-xs text-gray-400">{folder.fileCount}</span>
          )}
        </div>

        {/* 子文件夹 */}
        {isExpanded && hasChildren && (
          <div>
            {folder.children!.map((child) => renderFolder(child, level + 1))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="h-full flex flex-col bg-white border-r border-gray-200">
      {/* 头部 */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between mb-3">
          <h3 className="font-semibold text-gray-700">文件夹</h3>
          <button
            onClick={() => {
              setParentFolderId(null);
              setShowCreateModal(true);
            }}
            className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
          >
            + 新建
          </button>
        </div>

        {/* 根目录 */}
        <div
          className={`flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-100 rounded transition-colors ${
            currentFolderId === null ? 'bg-blue-50 text-blue-600' : ''
          }`}
          onClick={() => selectFolder(null)}
          onContextMenu={(e) => handleContextMenu(e, null)}
        >
          <span className="text-xl">🏠</span>
          <span className="text-sm font-medium">全部文件</span>
        </div>
      </div>

      {/* 文件夹树 */}
      <div className="flex-1 overflow-y-auto p-2">
        {folders.map((folder) => renderFolder(folder))}
      </div>

      {/* 右键菜单 */}
      {contextMenu && (
        <div
          className="fixed bg-white border border-gray-200 rounded-lg shadow-lg py-1 z-50"
          style={{ left: contextMenu.x, top: contextMenu.y }}
        >
          <button
            onClick={() => {
              setParentFolderId(contextMenu.folder?._id || null);
              setShowCreateModal(true);
              setContextMenu(null);
            }}
            className="w-full px-4 py-2 text-left text-sm hover:bg-gray-100 flex items-center gap-2"
          >
            ➕ 新建子文件夹
          </button>
          {contextMenu.folder && (
            <>
              <button
                onClick={() => {
                  handleRenameFolder(contextMenu.folder!);
                  setContextMenu(null);
                }}
                className="w-full px-4 py-2 text-left text-sm hover:bg-gray-100 flex items-center gap-2"
              >
                ✏️ 重命名
              </button>
              <button
                onClick={() => {
                  handleDeleteFolder(contextMenu.folder!);
                  setContextMenu(null);
                }}
                className="w-full px-4 py-2 text-left text-sm hover:bg-gray-100 flex items-center gap-2 text-red-600"
              >
                🗑️ 删除
              </button>
            </>
          )}
        </div>
      )}

      {/* 创建文件夹弹窗 */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-96">
            <h3 className="text-lg font-semibold mb-4">创建文件夹</h3>
            
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                文件夹名称
              </label>
              <input
                type="text"
                value={newFolderName}
                onChange={(e) => setNewFolderName(e.target.value)}
                placeholder="请输入文件夹名称"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                autoFocus
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    handleCreateFolder();
                  }
                }}
              />
            </div>

            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                文件夹颜色
              </label>
              <div className="flex gap-2">
                {['#3B82F6', '#EF4444', '#10B981', '#F59E0B', '#8B5CF6', '#EC4899'].map((color) => (
                  <button
                    key={color}
                    onClick={() => setNewFolderColor(color)}
                    className={`w-8 h-8 rounded-full border-2 ${
                      newFolderColor === color ? 'border-gray-800' : 'border-gray-300'
                    }`}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>

            <div className="flex justify-end gap-2">
              <button
                onClick={() => {
                  setShowCreateModal(false);
                  setNewFolderName('');
                  setNewFolderColor('#3B82F6');
                  setParentFolderId(null);
                }}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                取消
              </button>
              <button
                onClick={handleCreateFolder}
                disabled={!newFolderName.trim()}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default FolderTree;

